package tech.veedo.munchkin.verifications.backend.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import tech.veedo.munchkin.beans.backend.Mapping;
import tech.veedo.munchkin.constants.Operation;
import tech.veedo.munchkin.verifications.backend.MappingVerify;

@Slf4j
@Service
public class MappingVerifyImpl implements MappingVerify {

    @Override
    public boolean verify(Operation operation, Mapping mapping) {
        switch (operation) {
            case ADD:
                return addVerify(mapping);
            case UPDATE:
                return updateVerify(mapping);
            default:
                return true;
        }
    }

    private boolean addVerify(Mapping mapping) {
        nameNotNull(mapping.getName());
        workflowIDNotNull(mapping.getWorkflowID());
        orgCodeNotNull(mapping.getOrgCode());
        hookMIDNotNullWhenIsHook(mapping.isHook(), mapping.getHookMappingID());
        return true;
    }

    private boolean updateVerify(Mapping mapping) {
        idNotNull(mapping.getId());
        nameNotNull(mapping.getName());
        hookMIDNotNullWhenIsHook(mapping.isHook(), mapping.getHookMappingID());
        return true;
    }

    private void idNotNull(Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new NullPointerException("实体工作流id为空");
        }
    }

    private void nameNotNull(String mappingName) {
        if (StringUtils.isBlank(mappingName)) {
            throw new NullPointerException("实体工作流名称为空");
        }
    }

    private void workflowIDNotNull(Long workflowID) {
        if (ObjectUtils.isEmpty(workflowID)) {
            throw new NullPointerException("实体工作流的父级(顶层工作流)的id为空");
        }
    }

    private void orgCodeNotNull(String orgCode) {
        if (StringUtils.isBlank(orgCode)) {
            throw new NullPointerException("实体工作流的所属机构编码为空");
        }
    }

    private void hookMIDNotNullWhenIsHook(boolean isHook, Long hookMID) {
        if (isHook && ObjectUtils.isEmpty(hookMID)) {
            throw new NullPointerException("实体工作流属性'hook' == true时，挂接的实体工作流id为空");
        }
    }

}
